<template>
  <div class="aside">
    <el-header class="logo">
      <i class="el-icon-fa-home pointer" v-show="collapse" @click="home"></i>
      <span class="pointer" v-show="!collapse" @click="home">
        Logo
      </span>
    </el-header>
    <el-menu :collapse="collapse" :unique-opened="true" class="nav-menu" router :default-active="$route.path" :default-openeds="openeds">
      <template v-for="menu in navs">
        <el-submenu :index="menu.menuId + ''" v-if="menu.list" :key="menu.menuId">
          <template slot="title">
            <i :class="menu.icon"></i>
            <span>{{ menu.name }}</span>
          </template>
          <el-menu-item v-for="sub in menu.list" :index="sub.url" :key="sub.menuId" :route="sub.url">
            <template slot="title">
              <i :class="sub.icon"></i>
              <span>{{ sub.name }}</span>
            </template>
          </el-menu-item>
        </el-submenu>
        <el-menu-item v-else :index="menu.url" :route="menu.url" :key="menu.menuId">
          <i :class="menu.icon"></i>
          <span slot="title">{{ menu.name }}</span>
        </el-menu-item>
      </template>
    </el-menu>
  </div>
</template>
<script>
  import { mapState } from "vuex";

  export default {
    name: "nav-menu",
    props: {
      menus: Array
    },
    data() {
      return {
        initPath: this.$route.path
      };
    },
    computed: {
      ...mapState(["collapse"]),
      navs() {
        return this.filter(this.menus);
      },
      openeds() {
        const subs = this.menus.reduce((total, item) => total.concat(item.list || []), []);
        const nav =  subs.find(item => item.url === this.initPath);
        if (!nav) {
          return [];
        }
        return [ nav.parentId + "" ];
      },
    },
    // updated() {
    //   const nav = this.getMenu(this.$route.path);
    //   nav && this.$refs.nav.open(nav.parentId + "");
    // },
    methods: {
      filter(menus) {
        menus.forEach(menu => {
          if (menu.list) {
            menu.list = menu.list.filter(({ url }) => url.startsWith("/"));
          }
        });
        return menus;
      },
      home() {
        this.$router.push("/home");
      },
      // getMenu(path) {
      //   const subs = this.menus.reduce((total, item) => total.concat(item.list || []), []);
      //   return subs.find(item => item.url === path);
      // },
    }
  };
</script>

<style scoped lang="less">
  @import "../../assets/vars";
  .el-menu-item.is-active{
    background-color: #ecf5ff;
  }
  .aside {
    display: flex;
    flex-direction: column;
  }

  .logo {
    flex: none;
    color: white;
    background-color: @baseBgColor;
    text-align: center;
    line-height: 60px;
    i {
      font-size: 1.2em;
    }
  }

  .nav-menu {
    flex: auto;
    overflow: auto;
    width: 200px;
    border-right: 0;
    &.el-menu--collapse {
      width: auto;
      overflow: visible;
    }
  }
</style>
